<template>
  <div class="login">
    <div class="login-view">
      <div class="left">
        <img class="logo" :src="require('@/assets/logo@2x.png')" />
        <div class="name">
          <h1 class="zh">研发云</h1>
          <h1 class="en">DevOps for Developers</h1>
        </div>
        <img class="bg" :src="require('@/assets/loginbg.png')" />
      </div>
      <div class="right">
        <div class="head-tools">
          <div class="head-tools-item">
            <img class="icon" :src="require('@/assets/chat_mini.png')" /><span
              >联系我们</span
            >
          </div>
        </div>
        <Form
          class="form"
          :model="accountLoginParams"
          ref="loginForm"
          :rules="rules"
        >
          <div class="title">登录</div>
          <FormItem prop="name" class="form-item">
            <div class="form-item-label">账号</div>
            <Input
              class="input1"
              placeholder="请输入账号"
              v-model="accountLoginParams.name"
            ></Input>
          </FormItem>
          <FormItem
            class="form-item"
            prop="password"
            v-if="loginType === 'account'"
          >
            <div class="form-item-label">密码</div>
            <Input
              class="input1"
              placeholder="请输入密码"
              type="password"
              v-model="accountLoginParams.password"
            ></Input>
          </FormItem>

          <!-- style="margin-bottom:10px;" -->
          <FormItem class="form-item" prop="captcha">
            <div class="form-item-label">验证码</div>
            <Input
              @keyup.enter.native="handleLogin"
              placeholder="请输入验证码"
              v-model="accountLoginParams.captcha"
              class="input1 input-with-select"
            >
              <div
                @click="getCaptcha(false)"
                slot="append"
                class="code_image_box"
              >
                <img :src="captchaCode.captcha" alt />
              </div>
            </Input>
          </FormItem>

          <FormItem class="form-item" style="margin-bottom: 10px">
            <div class="form-lint-box">
              <!-- <el-checkbox
                style="margin-right: auto"
                v-model="rememberPassChecked"
                >记住密码</el-checkbox
              > -->
              <div class="form-item-label">记住密码</div>
              <a class="link" @click="$router.push('/forgot')">忘记密码</a>

              <!-- <a class="link" type="primary" :underline="false"
                >注册账号</a
              > -->
            </div>
          </FormItem>

          <FormItem class="form-item" style="margin-bottom: 0px">
            <Button class="Button" @click.native="handleLogin" type="primary"
              >登 录</Button
            >
          </FormItem>

          <div class="foot">
            还没有账号？<a class="link" href="">了解申请流程&gt;</a>
          </div>
        </Form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Ref } from "vue-property-decorator";
import { UserModule } from "@/store/modules/user";
import { encrypt, decryptByAES } from "@/utils/crypto";
import { UserManagementService } from "@/openApi/user-management.v1";
import { accountValidator, passwordValidator } from "@/utils/validate";
import { Form } from "view-design";
import { RoleType } from "@/models/user";

@Component({
  components: {}
})
export default class Login extends Vue {
  @Ref("loginForm") loginForm?: Form;
  rememberPassChecked = false; //记住密码
  captchaCode = {
    //验证码
    captcha: "",
    captchaId: ""
  };
  loginType = "account"; //登录方式

  accountLoginParams = {
    //账号登录参数
    name: "", //账户 rootadmin
    password: "", //密码 PnzD3KhhtzhuTbzP
    captcha: "", //验证码
    captchaId: "" //验证码Id
  };
  rules = {
    name: [{ required: true, validator: accountValidator, trigger: "blur" }],
    password: [{ validator: passwordValidator, trigger: "blur" }],
    captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
  };

  async getCaptcha() {
    const params = {};
    if (this.captchaCode.captchaId) {
      Object.assign(params, { captchaId: this.captchaCode.captchaId });
    }
    const resData = await UserManagementService.getCaptcha(params);
    console.log("验证码", resData);
    this.captchaCode = resData;
    this.accountLoginParams.captchaId = resData.captchaId;
  }
  //设置cookie
  setCookie(cName: string, cPwd: string, loginType: string, exdays: number) {
    const exdate = new Date(); //获取时间
    exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数

    this.saveCookie("uacname", cName, exdate);
    this.saveCookie("uacpassword", cPwd, exdate);
    this.saveCookie("uacloginType", loginType, exdate);
  }
  saveCookie(name: string, value: string, exdate: Date) {
    window.document.cookie =
      location.hostname +
      name +
      "=" +
      value +
      ";path=/;expires=" +
      exdate.toUTCString();
  }

  //读取cookie
  getCookie() {
    try {
      if (document.cookie.length > 0) {
        const arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (let i = 0; i < arr.length; i++) {
          const arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == location.hostname + "uacname") {
            this.accountLoginParams.name = decryptByAES(arr2[1]); //保存到保存数据的地方
          } else if (arr2[0] == location.hostname + "uacpassword") {
            this.accountLoginParams.password = decryptByAES(arr2[1]);
          } else if (arr2[0] == location.hostname + "uacloginType") {
            this.loginType = arr2[1];
          }
        }
        if (this.accountLoginParams.name) {
          this.rememberPassChecked = true;
        } else {
          this.rememberPassChecked = false;
        }
      }
    } catch (error) {
      console.log("error", error);
    }
  }
  //清除cookie
  clearCookie() {
    this.setCookie("", "", "", -1); //修改2值都为空天数为负1天就好了
  }

  handleLogin() {
    if (this.loginForm)
      this.loginForm.validate(async valid => {
        if (valid) {
          if (this.rememberPassChecked == true) {
            //传入账号名，密码，和保存天数3个参数
            this.setCookie(
              encrypt(this.accountLoginParams.name),
              encrypt(this.accountLoginParams.password),
              this.loginType,
              7
            );
          } else {
            //清空Cookie
            this.clearCookie();
          }

          let params: any = {};
          if (this.loginType === "account") {
            params = {
              loginType: this.loginType,
              accountLoginParams: {
                name: this.accountLoginParams.name,
                password: encrypt(this.accountLoginParams.password),
                captcha: this.accountLoginParams.captcha,
                captchaId: this.accountLoginParams.captchaId
              }
            };
          }

          UserModule.Login(params)
            .then(res => {
              console.log("登录成功", res);
              this.$Message.success({
                content: "登录成功",
                duration: 2
              });

              if (res.roleType == RoleType.USER) this.$router.push("/home"); //普通用户
              else if (res.roleType == RoleType.SYS) this.$router.push("/home"); //系统用户
            })
            .catch(err => {
              console.log("异常", err);
              this.getCaptcha();
            });
        }
      });
  }
  created() {
    this.getCaptcha();
    this.getCookie();
  }
}
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  min-height: 700px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #dee5f5;
  // background: url("../../assets/bg.jpg") no-repeat center center fixed;
  background-size: cover;
  .code_image_box {
    cursor: pointer;
    width: 100px;
    // height: 34px;
    > img {
      height: 100%;
      width: 100%;
    }
  }
  .login-view {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 100%;
    .left {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      flex: 1;
      position: relative;
      .logo {
        position: absolute;
        left: 50px;
        top: 41px;
        width: 109px;
        height: 32px;
      }
      .name {
        position: absolute;
        left: 95px;
        top: 152px;
        text-align: left;
        line-height: 1;
        .zh {
          color: #30353a;
          font-weight: 400;
          font-family: sans-serif;
          font-size: 34px;
          margin-bottom: 23px;
        }
        .en {
          color: #8894a1;
          font-family: sans-serif;
          font-size: 24px;
          font-weight: 400;
        }
      }
      .bg {
        width: 665px;
        height: 445px;
      }
    }
    .right::v-deep {
      width: 420px;
      background-color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 1;
      position: relative;
      .head-tools {
        position: absolute;
        right: 49px;
        top: 49px;
        cursor: pointer;
        .head-tools-item {
          .icon {
            margin-right: 10px;
          }
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%;
        box-sizing: border-box;
        padding: 10px 56px;
        .form-item {
          width: 100%;
          margin-bottom: 20px;
          .form-lint-box {
            div {
              display: inline;
            }
          }
          .form-item-label {
            font-size: 14px;
            font-family: sans-serif;
            font-weight: 400;
            color: #636c76;
            line-height: 1;
            margin-bottom: 7px;
          }
          .ivu-form-item-error-tip {
            position: absolute;
            top: 0;
            left: 0;
            text-align: right;
            width: 100%;
            line-height: 1;
            padding-top: 0px;
            color: #ed4014;
          }
        }
      }
      .title {
        font-size: 24px;
        font-family: sans-serif;
        font-weight: 400;
        color: #30353a;
        margin-bottom: 61px;
      }
      .foot {
        margin-top: 57px;
        font-size: 14px;
        font-family: sans-serif;
        font-weight: 400;
        color: #636c76;
        line-height: 1;
      }
      .Input__inner {
        background-color: rgb(0, 0, 0, 0);

        border: 1px solid rgb(144 216 255 / 55%);
      }
      .Button {
        border-radius: 6px;
        border: 0;
        text-transform: uppercase;
        font-size: 16px;
        font-family: sans-serif;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
        width: 100%;
        height: 45px;
        background: #3069fc;
        box-shadow: 0px 9px 18px 0px rgba(97, 186, 254, 0.1);
        transition-property: background, color;
        transition-duration: 0.2s;
      }
      .Button:hover {
        color: white !important;
        background: #307cfb;
        cursor: pointer;
        transition-property: background, color;
        transition-duration: 0.2s;
      }
    }
  }
}
</style>
